package com.rename.wechat.weixin.utils;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.jasper.tagplugins.jstl.core.Url;

import com.mysql.fabric.Response;
import com.rename.wechat.model.AccessToken;
import com.rename.wechat.weixin.WeixinConfig;
import com.rename.wechat.weixin.menu.Button;
import com.rename.wechat.weixin.menu.ClickButton;
import com.rename.wechat.weixin.menu.ComplexButton;
import com.rename.wechat.weixin.menu.Menu;
import com.rename.wechat.weixin.menu.ViewButton;

import net.sf.json.JSONObject;

public class WeixinUtil {
	
	// 获取access_token接口url
	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	
	// 多媒体文件上传接口url
	private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
	
	// 自定义菜单创建接口url
	private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	
	// 自定义菜单查询接口url
	private static final String GET_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
	
	// 自定义菜单删除接口url
	private static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

	/**
	 * http get请求
	 * @param url
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static JSONObject doGetStr(String url) throws ClientProtocolException, IOException{
		JSONObject jsonObject = null;
		// 建立连接
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResp = httpClient.execute(httpGet);
		// 获取响应
		HttpEntity httpEntity = httpResp.getEntity();
		if(httpEntity != null){
			String result = EntityUtils.toString(httpEntity, "UTF-8");
			jsonObject = JSONObject.fromObject(result);
		}
		
		// 关闭流，释放资源
		httpClient.close();
		httpClient = null;
		
		return jsonObject;
	}
	
//	public static JSONObject doGetStr(String urlStr){
//		JSONObject jsonObject = null;
//		
//		// 建立连接
//		try {
//			URL url = new URL(urlStr);
//			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		
//		// 处理流
//		
//		// 关闭流，释放资源
//		return jsonObject;
//	}
	
	/**
	 * http post请求
	 * @param url
	 * @param outStr
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static JSONObject doPostStr(String url, String outStr) throws ClientProtocolException, IOException{
		JSONObject jsonObject = null;
		// 建立连接
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new StringEntity(outStr, "UTF-8"));
		// 获取响应
		HttpResponse httpResp = httpClient.execute(httpPost);
		String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
		jsonObject = JSONObject.fromObject(result);
		
		// 关闭流，释放资源
		httpClient.close();
		httpClient = null;
		
		return jsonObject;
	}
	
	/**
	 * 获取access_token全局唯一票据
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static AccessToken getAccessToken() throws ClientProtocolException, IOException{
		String url = ACCESS_TOKEN_URL;
		url = url.replace("APPID", WeixinConfig.APPID).replace("APPSECRET", WeixinConfig.APPSECRET);
		JSONObject jsonObject = doGetStr(url);
		String access_token = jsonObject.getString("access_token");
		AccessToken accessToken = null;
		
		// 检查返回值是否正确
		if(!StringUtils.isBlank(access_token)){
			// 创建AccessToken对象
			accessToken = new AccessToken();
			accessToken.setToken(access_token);
			accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
		}
		
		return accessToken;
		
	}
	
	/**
	 * 组装菜单
	 * @return
	 */
	public static Menu initMenu(){
		Menu menu = new Menu();
		ClickButton button11 = new ClickButton();
		button11.setName("click菜单");
		button11.setType("click");
		button11.setKey("11");
		
		ViewButton button21 = new ViewButton();
		button21.setName("view菜单");
		button21.setType("view");
		button21.setUrl("http://www.imooc.com");
		
		ClickButton button31 = new ClickButton();
		button31.setName("扫码事件");
		button31.setType("scancode_push");
		button31.setKey("31");
		
		ClickButton button32 = new ClickButton();
		button32.setName("地理位置");
		button32.setType("location_select");
		button32.setKey("32");
		
		ComplexButton button3 = new ComplexButton();
		button3.setName("菜单");
		button3.setSub_button(new Button[]{ button31, button32 });
		
		menu.setButton(new Button[]{ button11, button21, button3 });
		return menu;
	}
	
	/**
	 * 创建自定义菜单
	 * @param token
	 * @param menu
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static int createMenu(String token, String menu) throws ParseException, IOException{
		int result = 0;
		String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = doPostStr(url, menu);
		System.out.println(menu);
		if(jsonObject != null){
			result = jsonObject.getInt("errcode");
		}
		return result;
	}
	
	public static JSONObject getMenu(String token) throws ClientProtocolException, IOException{
		String url = GET_MENU_URL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = doGetStr(url);
		return jsonObject;
	}
	
	public static int deleteMenu(String token) throws ClientProtocolException, IOException{
		int result = 0;
		String url = DELETE_MENU_URL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = doGetStr(url);
		if(jsonObject != null){
			result = jsonObject.getInt("errcode");
		}
		return result;
	}
	
	/**
	 * 文件上传
	 * @param filePath
	 * @param accessToken
	 * @param type
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 * @throws KeyManagementException
	 */
	public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		File file = new File(filePath);
		if (!file.exists() || !file.isFile()) {
			throw new IOException("文件不存在");
		}

		String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);
		
		URL urlObj = new URL(url);
		//连接
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

		con.setRequestMethod("POST"); 
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false); 

		//设置请求头信息
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");

		//设置边界
		String BOUNDARY = "----------" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

		StringBuilder sb = new StringBuilder();
		sb.append("--");
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");

		byte[] head = sb.toString().getBytes("utf-8");

		//获得输出流
		OutputStream out = new DataOutputStream(con.getOutputStream());
		//输出表头
		out.write(head);

		//文件正文部分
		//把文件已流文件的方式 推入到url中
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();

		//结尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定义最后数据分隔线

		out.write(foot);

		out.flush();
		out.close();

		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		String result = null;
		try {
			//定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				reader.close();
			}
		}

		JSONObject jsonObj = JSONObject.fromObject(result);
		System.out.println(jsonObj);
		String typeName = "media_id";
		if(!"image".equals(type)){
			typeName = type + "_media_id";
		}
		String mediaId = jsonObj.getString(typeName);
		return mediaId;
	}
	
}
